package com.ita.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ita.pojo.Customer;
import com.ita.service.CustomerManger;

public class CustomerManagerImpl implements CustomerManger {

	private List<Customer> customers = new ArrayList<Customer>();

	@Override
	public Customer addCustomer(Customer c) {

		synchronized (customers) {
			c.setId(UUID.randomUUID().toString());
			customers.add(c);
		}
		return c;
	}

	@Override
	public List<Customer> findAllCustomers() {
		return customers;
	}

	@Override
	public Customer updateCustomer(Customer c) {

		for (int i = 0; i < customers.size(); i++) {
			Customer old = customers.get(i);
			if (c.getId().equals(old.getId())) {
				customers.remove(old);
				customers.add(i, c);
				break;
			}
		}
		return c;
	}

	@Override
	public String deleteCustomer(String jsonString) {

		ObjectMapper mapper = new ObjectMapper();
		JsonNode node = null;
		try {
			node = mapper.readTree(jsonString);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String id = node.get("id").toString().split("\"")[1];
		for (Customer customer : customers) {
			if (id.equals(customer.getId())) {
				customers.remove(customer);
				break;
			}
		}
		return jsonString;
	}

	@Override
	public Customer getCustomer(String jsonString) {
		// TODO Auto-generated method stub
		ObjectMapper mapper = new ObjectMapper();
		JsonNode node = null;
		Customer c = null;
		try {
			node = mapper.readTree(jsonString);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String id = node.get("id").toString().split("\"")[1];
		for (Customer customer : customers) {
			if (id.equals(customer.getId())) {
				c = customer;
				break;
			}
		}
		return c;
	}

}
